<template>
  <div class="warp-box clearfix">
    <div class="warp-con">
      <div class="header">
        <div class="headerWrapper">
          <div class="search">
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item>
                <el-date-picker v-model="time" type="daterange" start-placeholder="创建时间" range-separator="至"
                                end-placeholder="创建时间" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"
                                :default-time="['00:00:00', '23:59:59']" />
              </el-form-item>
              <el-form-item>
                <el-input placeholder="请输入种名" v-model="searchForm.speciesName" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="upload" @click="query">查询</el-button>
                <el-button v-if="addBtn" type="primary" class="upload" @click="addDialog">新增</el-button>
                <el-button v-if="importBtn" type="primary" @click="dialogImportVisible = true">导入</el-button>
                <el-dropdown @command="exportTmpVal" class="exportMenu" trigger="click" v-if="exportBtn">
                  <el-button type="primary">
                    导出<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown" style="background-color: rgb(21 120 176)">
                    <el-dropdown-item :command="false">
                      选择
                    </el-dropdown-item>
                    <el-dropdown-item :command="true">
                      全部
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="content">
        <el-table ref="multipleTable" border stripe :data="tableData" v-loading="loading" element-loading-text="拼命加载中"
                  element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
                  @select="handleSelect" @select-all="handleSelectAll" class="tableLine" :max-height="635">
          <el-table-column align="center" type="selection" v-if="exportBtn" />
          <el-table-column prop="createDate" show-overflow-tooltip label="创建时间" align="center" />
          <el-table-column prop="speciesName" show-overflow-tooltip label="种名" align="center" />
          <el-table-column prop="familyName" show-overflow-tooltip label="科名" align="center" />
          <el-table-column prop="source" show-overflow-tooltip label="来源" align="center" />
          <el-table-column prop="purpose" show-overflow-tooltip label="主要用途" align="center" />
          <el-table-column fixed="right" label="操作" align="center" width="200">
            <template slot-scope="scope">
              <span class="pointer" @click="read(scope.row)">查看</span>
              <span v-if="updateBtn" class="pointer" @click="updateDialog(scope.row)"><i class="line"></i>修改</span>
              <span v-if="deleteBtn" class="pointer" @click="removeData(scope.row)"><i class="line"></i>删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging">
        <el-pagination :page-size="pageSize" :page-sizes="[10,20,50]" :total="tableDataTotalCount" @current-change="handleCurrentChange"
                       @size-change="handleSizeChange" background layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
    </div>
    <el-dialog :visible.sync="dialogFormVisible" width="650px" :title="dialogTitle" :before-close="cancel"
      :close-on-click-modal="false">
      <el-form :model="addForm" ref="ruleForm" label-width="140px" class="demo-ruleForm">
        <div class="form-table_col2">
          <table border="1" width="100%">
            <tr>
              <td class="form-item_label">种名</td>
              <td>
                <el-input v-model="addForm.speciesName" :disabled="disabled" />
              </td>
            </tr>
            <tr>
              <td>拉丁名</td>
              <td>
                <el-input class="oblique" v-model="addForm.latinName" :disabled="disabled"/>
              </td>
            </tr>
            <tr>
              <td>科名</td>
              <td>
                <el-input v-model="addForm.familyName" :disabled="disabled" />
              </td>
            </tr>
            <tr>
              <td>科拉丁名</td>
              <td>
                <el-input class="oblique" v-model="addForm.familyLatinName" :disabled="disabled" />
              </td>
            </tr>
            <tr>
              <td>属名</td>
              <td>
                <el-input v-model="addForm.genericName" :disabled="disabled" />
              </td>
            </tr>
            <tr>
              <td>属拉丁名</td>
              <td>
                <el-input class="oblique" v-model="addForm.genericLatinName" :disabled="disabled" />
              </td>
            </tr>
            <tr>
              <td>别名</td>
              <td>
                <el-input v-model="addForm.alias" :disabled="disabled" />
              </td>
            </tr>
            <tr>
              <td>来源</td>
              <td>
                <el-select v-model="addForm.source" :disabled="disabled" clearable>
                  <el-option v-for="(item, i) in source" :label="item.label" :value="item.value" :key="i" />
                </el-select>
              </td>
            </tr>
            <tr>
              <td>种类</td>
              <td>
                <el-select v-model="addForm.speciesType" :disabled="disabled" clearable>
                  <el-option v-for="(item, i) in speciesType" :label="item.label" :value="item.value" :key="i" />
                </el-select>
              </td>
            </tr>
            <tr>
              <td>树种类别</td>
              <td>
                <el-select multiple filterable allow-create default-first-option placeholder="请选择树种类别" v-model="addForm.category"
                  :disabled="disabled">
                  <el-option v-for="(item, i) in category" :label="item" :value="item" :key="i" />
                </el-select>
              </td>
            </tr>
            <tr>
              <td>地理分布</td>
              <td>
                <el-input v-model="addForm.geoDis" :disabled="disabled" />
              </td>
            </tr>
            <tr>
              <td>主要用途</td>
              <td>
                <el-select multiple placeholder="请选择" v-model="addForm.purpose" :disabled="disabled">
                  <el-option v-for="(item, i) in purpose" :label="item.label" :value="item.value" :key="i" />
                </el-select>
              </td>
            </tr>
            <tr>
              <td>排序</td>
              <td>
                <el-input-number v-model="addForm.sortNo" :disabled="disabled" />
              </td>
            </tr>
            <!--<tr>
              <td>隶属大类</td>
              <td>
                <el-input v-model="addForm.dependent" :disabled="disabled" />
              </td>
            </tr>-->
            <tr>
              <td style="display:table-cell;vertical-align: middle">备注</td>
              <td>
                <el-input type="textarea" v-model="addForm.remarks" :disabled="disabled"/>
              </td>
            </tr>
          </table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogEdit !== 'read'" class="dialogBtn" type="primary" @click="saveData">
          <span v-if="dialogEdit === 'edit'">修 改</span>
          <span v-else>保 存</span>
        </el-button>
        <el-button type="primary" @click="cancel" class="dialogBtn">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导入物种" :visible.sync="dialogImportVisible" width="30%" class="import" :close-on-click-modal="false">
      <div style="text-align: center">
        <el-upload class="upload-demo" drag :action="uploadAction" :show-file-list="false" :headers="uploadHeader"
          :before-upload="beforeUpload" :on-success="handleSuccess">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传xls/xlsx文件，
            <el-button type="text" @click="downloadExcel">下载模板</el-button>
          </div>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import resourceApi from '@/api/resourceApi'

  export default {
    name: 'speciesManage',
    data() {
      return {
        time: [],
        loading: false,
        searchForm: {
          speciesName: null
        },
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0,
        tableData: [],
        addForm: {},
        dialogTitle: null,
        dialogEdit: null,
        dialogFormVisible: false,
        dialogImportVisible: false,
        purpose: [{
            value: '用材',
            label: '用材'
          },
          {
            value: '食用',
            label: '食用'
          },
          {
            value: '药用',
            label: '药用'
          },
          {
            value: '防护',
            label: '防护'
          },
          {
            value: '观赏',
            label: '观赏'
          },
          {
            value: '其他',
            label: '其他'
          }
        ],
        source: [{
          value: '乡土',
          label: '乡土'
        }, {
          value: '外来',
          label: '外来'
        }],
        speciesType: [{
          value: '亚种',
          label: '亚种'
        }, {
          value: '变种',
          label: '变种'
        }],
        category: ['国家Ⅰ级重点保护植物', '国家Ⅱ级重点保护植物', '省级重点保护植物', '我国特有树种', '国外引进树种', '有开发利用潜力'],
        disabled: false,
        addBtn: false,
        updateBtn: false,
        deleteBtn: false,
        importBtn: false,
        exportBtn: false,
        uploadHeader: {
          token: `${window.localStorage.token}`
        },
        uploadAction: process.env.SURVEY_DOMAIN + '/gr/speciesManage/importExcel',
        onlyId: []
      }
    },
    computed: {
      tableDataTotalCount() {
        return this.totalCount ? this.totalCount : 0
      }
    },
    created() {
      this.initBtn()
      this.findPage()
    },
    methods: {
      query() {
        this.pageIndex = 1;
        this.findPage()
      },
      findPage() {
        this.loading = true
        let time = this.time;
        let params = this.searchForm;
        params.pageSize = this.pageSize;
        params.pageIndex = this.pageIndex;
        params.startDate = time ? time[0] : null;
        params.endDate = time ? time[1] : null;
        params.sort = 'sortNo';
        params.order = 'ASC';
        resourceApi.findSpeciesPage(params).then(res => {
          this.loading = false;
          let result = res.data.result;
          if (res.data.message === 'success' && result) {
            this.tableData = result.rows
            this.totalCount = result.totalCount

            let onlyId = this.onlyId
            if (onlyId.length > 0) {
              this.$nextTick(() => {
                this.tableData.forEach((row) => {
                  for (let i in onlyId) {
                    let id = onlyId[i];
                    if (row.id === id) {
                      this.$refs.multipleTable.toggleRowSelection(row);
                      break;
                    }
                  }
                });
              });
            }
          } else {
            this.tableData = []
            this.totalCount = 0
          }
        })
      },
      pager(val) {
        this.pageIndex = val
        this.findPage()
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.findPage()
      },
      handleCurrentChange(val) {
        this.pageIndex = val
        this.findPage()
      },
      addDialog() {
        this.dialogEdit = 'add'
        this.dialogTitle = '新增物种'
        let user = JSON.parse(localStorage.getItem('user'))
        this.$set(this.addForm, 'registrant', user.userName)
        this.$set(this.addForm, 'registrantId', user.userId)
        this.dialogFormVisible = true
      },
      saveData() {
        if (!this.addForm.speciesName) {
          this.$message({
            message: '请输入物种名',
            type: 'warning'
          })
          return false
        }
        let params = Object.assign({}, this.addForm)
        if (params.category != null) {
          params.category = params.category.toString()
        }
        if (params.purpose != null) {
          params.purpose = params.purpose.toString()
        }
        this.showLoading()
        params.sortNo = params.sortNo ? params.sortNo : 0
        resourceApi.saveSpecies(params).then((res) => {
          this.hideLoading()
          let message = this.dialogEdit === 'edit' ? '修改' : '保存'
          if (res.data.message === 'success') {
            this.query()
            this.cancel()
            this.$notify({
              title: '消息',
              message: (message + '成功！'),
              position: 'bottom-right',
              showClose: false,
              type: 'success'
            })
          } else {
            this.$notify.error({
              title: '消息',
              message: message + '失败'
            })
          }
        })
      },
      read(row) {
        this.disabled = true
        this.dialogEdit = 'read'
        this.dialogTitle = '查看物种'
        this.getSpeciesInfo(row)
      },
      updateDialog(row) {
        this.dialogEdit = 'edit'
        this.dialogTitle = '修改物种'
        this.getSpeciesInfo(row)
      },
      async getSpeciesInfo(row) {
        const res = await resourceApi.getSpecies(row.id)
        if (res.data.message === 'success') {
          this.dialogFormVisible = true
          this.addForm = res.data.result
          if (this.addForm.category != null && this.addForm.category != '') {
            const arr = this.addForm.category.split(',')
            this.addForm.category = arr
          }
          if (this.addForm.purpose != null && this.addForm.purpose != '') {
            const arr1 = this.addForm.purpose.split(',')
            this.addForm.purpose = arr1
          }
        }
      },
      removeData(row) {
        let tips = ''
        if (row) {
          tips = `此操作将删除: ${row.speciesName}, 是否继续?`
        } else {
          return
        }
        this.$confirm(tips, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          resourceApi.deleteSpecies(row.id).then((res) => {
            if (res.data.message === 'success') {
              this.query()
              this.$notify({
                title: '消息',
                message: ('删除成功！'),
                position: 'bottom-right',
                showClose: false,
                type: 'success'
              })

            }
          })
        }).catch((error) => {
          console.log(error)
        })
      },
      cancel() {
        this.addForm = {}
        this.disabled = false
        this.dialogFormVisible = false
      },
      showLoading() {
        this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      },
      hideLoading() {
        this.$loading().close()
      },
      initBtn() {
        let permissionBtn = JSON.parse(localStorage.permissionBtn)
        this.addBtn = permissionBtn['species_add']
        this.updateBtn = permissionBtn['species_update']
        this.deleteBtn = permissionBtn['species_delete']
        this.importBtn = permissionBtn['species_import']
        this.exportBtn = permissionBtn['species_export']
      },
      downloadExcel() {
        resourceApi.downloadExcel('/gr/speciesManage/downloadExcel', null)
      },
      beforeUpload(file) {
        let flag = false
        let name = file.name
        if (name.indexOf('.') > -1) {
          let suffix = name.substring(name.lastIndexOf('.') + 1, name.length)
          if (suffix === 'xls' || suffix === 'xlsx') {
            flag = true
          }
        }
        if (!flag) {
          this.$message({
            message: '只能上传xls/xlsx文件',
            type: 'warning'
          });
        } else {
          this.showLoading()
        }
        return flag
      },
      handleSuccess(res, file, fileList) {
        this.hideLoading()
        if (res.message === 'success') {
          this.query()
          this.dialogImportVisible = false
          this.$message({
            message: '导入成功',
            type: 'success'
          });
        } else {
          let message = res.message
          if (message && message.indexOf(':') > -1) {
            message = message.substring(message.lastIndexOf(':') + 1, message.length)
          }
          this.$message.error(message ? message : '导入失败');
        }
      },
      handleSelect(selection, row) {
        let id = row.id;
        let checked = false;
        for (let i in selection) {
          let item = selection[i];
          if (item.id === id) {
            checked = true;
            break;
          }
        }
        if (checked) {
          this.onlyId.push(id);
        } else {
          let index = this.onlyId.indexOf(id)
          this.onlyId.splice(index, 1);
        }
      },
      handleSelectAll(selection) {
        if (selection.length > 0) {
          for (let i in selection) {
            let item = selection[i]
            if (this.onlyId.indexOf(item.id) === -1) {
              this.onlyId.push(item.id)
            }
          }
        } else {
          let data = this.tableData
          for (let i in data) {
            let item = data[i]
            let index = this.onlyId.indexOf(item.id)
            if (index !== -1) {
              this.onlyId.splice(index, 1)
            }
          }
        }
      },
      clearSelection() {
        this.onlyId = []
        this.$refs.multipleTable.clearSelection()
      },
      async exportTmpVal(isAll) {
        if (!isAll) {
          if (this.onlyId.length === 0) {
            this.$message({
              message: "请选择需要导出的数据",
              type: "warning",
            });
            return false;
          }
        }

        let loading = this.$loading({
          lock: true,
          text: '数据导出中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        let time = this.time
        let params = {
          isAll: isAll,
          onlyId: this.onlyId,
          start: time ? time[0] : null,
          end: time ? time[1] : null,
          name: this.searchForm.speciesName
        }
        let url = '/gr/speciesManage/exportExcel'
        await resourceApi.downloadExcel(url, params)
        loading.close()
        this.clearSelection()
      },
    }
  }
</script>
<style lang="less" scoped>
  .search {
    & /deep/ .el-form-item__label {
      font-size: 1.8rem;
    }
  }

  .el-form-item__label {
    padding: 0 20px 0 0 !important;
  }

  .content {
    margin-top: 10px;

    & /deep/ .el-checkbox__inner {
      height: 20px;
      width: 20px;
      font-size: 28px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      background: none;
    }

    & /deep/ .el-tooltip__popper {
      background-color: red;
    }

    & /deep/ .el-checkbox__inner::after {
      border-width: 2px;
      /* border-color: black; */
      height: 6px;
      left: 6px;
      top: 3px;
      width: 4px;
    }

    & /deep/ .el-checkbox__input.is-indeterminate .el-checkbox__inner::before {
      top: 8px;
      background: white;
    }
  }

  .line {
    display: inline-flex;
    height: 21px;
    width: 1px;
    background: rgba(0, 255, 255, 1);
    margin: 0 10px;
    vertical-align: middle;
  }

  .dialogBtn {
    font-size: 1.6rem;

    &:hover {
      background: rgba(12, 161, 151, 1);
    }
  }

  .import {
    /deep/ .el-dialog__body {
      border-bottom: 1px solid #1f5aab;
    }
  }

  .exportMenu {
    margin-left: 10px;
  }

  /deep/ .el-dropdown-menu__item:focus,
  .el-dropdown-menu__item:not(.is-disabled):hover {
    color: #ffffff;
    background-color: #32f1ff16;
  }
</style>
<style lang="less">
  /**
     * 修改样式   覆盖默认的饿了么全局样式
     */
  .el-upload-dragger {
    background-color: transparent;
  }

  .el-form-item__label {
    padding: 0 20px 0 0 !important;
  }
</style>
